import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, Button, Switch, Select, notification } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";

import { SearchCol, SearchRow } from '@/styled/form';
import { inject_unount } from '@/utils/middleware';
import styles from '@/styled/form.less';
import Link from 'umi/link';

import { DICT } from '../enum'

const Option = Select.Option;

interface IProps extends FormComponentProps {
  dispatch?: Function;
  history?: any;
  location?: any;
  dict?: any;
  data?: {
    id: string;
    users: Array<any>;
    name: string;
    state: string | number;
    setStateName: string;
  };
  cond?: any;
  users?: Array<any>;
  match?: {
    params: {
      id: number
    }
  };
}

@connect(({ task_month, routing }) => ({
  users: task_month.users,
  cond: task_month.cond,
  location: routing.location || {}
}))
@inject_unount
class FormItem extends Component<IProps, any> {
  state = {};

  componentDidMount() {

    const { dispatch } = this.props;
    dispatch({
      type: 'task_month/initTask', payload: {
      }
    })

    const { form, data, location } = this.props;
    const session = JSON.parse(sessionStorage.getItem('form') || "{}")

    const isNew = location && location.state && location.state.isNew;
    const isGoto = location && location.state && location.state.goto;

    // data && data.name && form.setFieldsValue();
    let ans = {}

    if (isNew && !isGoto) {
      ans = {
        state: true
      }
    } else if (!isNew && !isGoto) {
      ans = data ? {
        name: data.name,
        users: Array.isArray(data.users) ? data.users.map(v => v.id) : [],
        state: data.state === 1
      } : {}
    } else {
      ans = session
    }

    form.setFieldsValue(ans)
  }

  cancel = e => {
    const { location, dispatch } = this.props;

    location && dispatch({
      type: 'task_month/cancel', payload: {
        id: location.pathname.split('/')[3],
        isNew: location.state && location.state.isNew
      }
    })
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { dispatch, location, form } = this.props;
    if (!location.state.isSet) {
      notification['warning']({
        message: `请设置检查内容`,
        description: '检查内容不能为空',
      });

      return;
    }

    form.validateFields((err, values) => {

      if (!err) {
        dispatch({
          type: 'task_month/update',
          payload: {
            id: location.pathname.split('/')[3],
            name: values.name,
            users: values.users,
            state: values.state === true ? 1 : 2,
            cycle: 3
          }
        })
      } else {
        notification['error']({
          message: `保存失败`,
          description: '字段验证不通过',
        });
      }
    })
  }

  handleSet = (e) => {
    const { form } = this.props;
    form.validateFields((err, values) => {
      sessionStorage.setItem('form', JSON.stringify(values))
    })
  }

  render() {
    const { form, data, users = [], location } = this.props;
    const { getFieldDecorator } = form;
    const isNew = location && location.state && location.state.isNew;
    const isSet = location && location.state && location.state.isSet;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 },
      },
    };

    const userObj = {};
    users.forEach(it => userObj[it.id] = it.realName)

    return (

      <Form onSubmit={this.handleSubmit}>
        <SearchCol span={18}>
          <SearchRow>
            <SearchCol span={24}>
              <Form.Item
                {...formItemLayout}
                label='任务名称'
              >
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请选择任务名称' }],
                })(
                  <Input placeholder='任务名称' />
                )}
              </Form.Item>
            </SearchCol>
            <SearchCol span={24}>
              <Form.Item
                {...formItemLayout}
                label='检查内容'
                className={styles.fileRequire}
              >
                <Link to={{ pathname: data && data.id ? `/data/task_month/${data.id}/target` : '', state: { isNew, isSet } }} onClick={this.handleSet}>
                  <Button type="primary">设置检查内容</Button> {(data ? data.setStateName : '') || ''}
                </Link>
              </Form.Item>
            </SearchCol>
            <SearchCol span={24}>
              <Form.Item
                {...formItemLayout}
                label='检查人员'
              >
                {getFieldDecorator('users', {
                  rules: [{ required: true, message: '请选择检查人员' }]
                })(
                  <Select mode="multiple" placeholder="请选择检查人员">
                    {
                      users.map(item => (
                        <Option value={item.id} key={item.id}>{item.realName}</Option>
                      ))
                    }
                  </Select>
                )}
              </Form.Item>
            </SearchCol>

            <SearchCol span={24}>
              <Form.Item
                {...formItemLayout}
                label='是否启用'
                className={styles.fileRequire}
              >
                {getFieldDecorator('state', {
                  valuePropName: 'checked',
                })(
                  <Switch />
                )}
              </Form.Item>
            </SearchCol>
          </SearchRow>
          <SearchRow type="flex" justify="start" style={{ padding: '40px 50px', width: '500px', position: 'fixed', bottom: '20px' }}>
            <Button onClick={this.cancel}>取消</Button>
            <Button style={{ marginLeft: '5%' }} type="primary" htmlType="submit">保存</Button>
          </SearchRow>
        </SearchCol>

      </Form>
    );
  }
}

const FormList = Form.create<IProps>()(FormItem);
export default FormList;
